// \u4e00-\u9fa5] 中文验证规则
// 导入表单校验插件
import wxValidate from 'wechat-validate'
Page({
  data: {
    point: '',
    building: '',
    room: '',
    name: '',
    gender: 1,
    mobile: '',
    idcardFrontUrl: '',
    idcardBackUrl: '',
  },
  rules: {
    name: [{
        required: true,
        message: '业主姓名不能为空!'
      },
      {
        pattern: /^[\u4e00-\u9fa5]{2,5}$/,
        message: '业主姓名只能为中文!'
      },
    ],
    mobile: [{
        required: true,
        message: '业主手机号不能为空!'
      },
      {
        pattern: /^1[3-8]\d{9}$/,
        message: '请填写正确的手机号!'
      },
    ],
    idcardFrontUrl: [{
      required: true,
      message: '请上传身份证国徽面!'
    }],
    idcardBackUrl: [{
      required: true,
      message: '请上传身份证照片面!'
    }],
  },
  behaviors: [wxValidate],
  onLoad({
    point,
    building,
    room,
    id
  }) {
    if (id) return this.getHouseDetail(id)
    this.setData({
      point,
      building,
      room
    })
  },
  async getHouseDetail(id) {
    const {
      code,
      data: houseDetail
    } = await wx.http.get('/room/' + id)
    if (code !== 10000) return wx.utils.toast()
    this.setData({
      ...houseDetail
    })
  },
  onChange(event) {
    this.setData({
      gender: event.detail,
    });
  },
  goList() {
    wx.reLaunch({
      url: '/house_pkg/pages/list/index',
    })
  },
  // 上传图片
  async uploadPicture(e) {
    console.log(e);
    // 区分正反面
    const type = e.mark.type
    const media = await wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sizeType: ['compressed']
    })
    console.log(media);
    // 上传图片
    wx.uploadFile({
      url: wx.http.baseURL + '/upload',
      filePath: media.tempFiles[0].tempFilePath,
      name: 'file',
      header: {
        // 需要传token
        Authorization: 'Bearer ' + getApp().token
      },
      success: (res) => {
        const data = JSON.parse(res.data)
        console.log(data);
        if (data.code !== 10000) return wx.utils.toast('上传图片失败')
        // 上传成功修改图片
        this.setData({
          [type]: data.data.url
        })

      }
    })

  },
  removePicture(ev) {
    // 移除图片的类型（身份证正面或反面）
    const type = ev.mark?.type
    this.setData({
      [type]: ''
    })
  },
  // 提交表单
  async submitForm() {
    // 校验数据
    if (!this.validate()) return
    // 通过结构 筛选数据
    const {
      __webviewId__,
      status,
      ...data
    } = this.data
    console.log(data);
    // 调用接口
    const res = await wx.http.post('/room', data)
    if (res.code !== 10000) return wx.utils.toast("提交数据失败")
    // 返回房屋列表
    wx.navigateBack({
      delta: this.data.id ? 2 : 4
    })
  }
})